package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {


    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    //添加购物车
    @Override
    public R<ShoppingCart> add(ShoppingCart shoppingCart) {
        //1.调用数据层方法根据用户的id与dishId或者是setmealId去查询该用户是否已经购买了该商品。
        ShoppingCart shoppingCartone = shoppingCartMapper.findByUserIdAndDidOrSid(shoppingCart);

        //2.如果是没有购买过该商品，创建一个新的购物项，补全信息，插入。
        if (shoppingCartone==null){
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.save(shoppingCart);
            shoppingCartone=shoppingCart;
        }else {
            //3.如果之前就已经购买过该商品，只需要数量+1 ，然后更新该记录
            shoppingCartone.setNumber(shoppingCartone.getNumber()+1);
            shoppingCartMapper.update(shoppingCartone);
        }
        return R.success(shoppingCartone);
    }


    //查看购物车
    @Override
    public R<List<ShoppingCart>> findCartByUserId(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findCartByUserId(userId);
        return R.success(shoppingCartList);
    }

    //清空购物车
    @Override
    public void cleanCart(Long userId) {
        shoppingCartMapper.cleanCart(userId);
    }

    //删除购物车
    @Override
    public R<ShoppingCart> delect(ShoppingCart shoppingCart) {
        ShoppingCart shoppingCart1 = shoppingCartMapper.findByUserIdAndDidOrSid(shoppingCart);
            if (shoppingCart1!=null){
                Integer number = shoppingCart1.getNumber();
                if (number>1){
                    number=shoppingCart1.getNumber()-1;
                    shoppingCart1.setNumber(number);
                    shoppingCartMapper.update(shoppingCart1);
                    return R.success(shoppingCart1);
                }else {
                    shoppingCartMapper.deleteByDishId(shoppingCart1.getDishId());
                    return R.success(shoppingCart);
                }
            }
        return R.success(shoppingCart);
    }


}
